<template>
  <Modal
    :title="role ? '编辑角色' : '创建角色'"
    size="lg"
    @close="$emit('close')"
  >
    <form @submit.prevent="handleSubmit" class="space-y-6">
      <!-- 基本信息 -->
      <div class="space-y-4">
        <h4 class="text-lg font-medium text-gray-900">基本信息</h4>
        
        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">
              角色名称 <span class="text-red-500">*</span>
            </label>
            <input
              v-model="formData.name"
              type="text"
              required
              class="input w-full"
              :class="{ 'border-red-500': errors.name }"
              placeholder="请输入角色名称"
            >
            <p v-if="errors.name" class="mt-1 text-sm text-red-600">
              {{ errors.name }}
            </p>
          </div>

          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">状态</label>
            <div class="flex items-center space-x-4">
              <label class="flex items-center">
                <input
                  v-model="formData.status"
                  type="radio"
                  value="active"
                  class="text-blue-600 border-gray-300 focus:ring-blue-500"
                >
                <span class="ml-2 text-sm text-gray-700">启用</span>
              </label>
              <label class="flex items-center">
                <input
                  v-model="formData.status"
                  type="radio"
                  value="inactive"
                  class="text-blue-600 border-gray-300 focus:ring-blue-500"
                >
                <span class="ml-2 text-sm text-gray-700">禁用</span>
              </label>
            </div>
          </div>
        </div>

        <div>
          <label class="block text-sm font-medium text-gray-700 mb-2">
            角色描述 <span class="text-red-500">*</span>
          </label>
          <textarea
            v-model="formData.description"
            required
            rows="3"
            class="input w-full"
            :class="{ 'border-red-500': errors.description }"
            placeholder="请输入角色描述"
          />
          <p v-if="errors.description" class="mt-1 text-sm text-red-600">
            {{ errors.description }}
          </p>
        </div>
      </div>

      <!-- 权限配置 -->
      <div class="space-y-4">
        <div class="flex items-center justify-between">
          <h4 class="text-lg font-medium text-gray-900">权限配置</h4>
          <div class="flex items-center space-x-2">
            <button
              type="button"
              @click="selectAllPermissions"
              class="text-sm text-blue-600 hover:text-blue-800"
            >
              全选
            </button>
            <span class="text-gray-300">|</span>
            <button
              type="button"
              @click="clearAllPermissions"
              class="text-sm text-blue-600 hover:text-blue-800"
            >
              清空
            </button>
          </div>
        </div>

        <div class="border border-gray-200 rounded-lg p-4 max-h-80 overflow-y-auto">
          <div
            v-for="category in permissionCategories"
            :key="category"
            class="mb-4 last:mb-0"
          >
            <div class="flex items-center mb-2">
              <input
                :id="`category-${category}`"
                type="checkbox"
                :checked="isCategorySelected(category)"
                :indeterminate="isCategoryIndeterminate(category)"
                @change="toggleCategory(category)"
                class="rounded border-gray-300 text-blue-600 shadow-sm focus:border-blue-300 focus:ring focus:ring-blue-200 focus:ring-opacity-50"
              >
              <label
                :for="`category-${category}`"
                class="ml-2 text-sm font-medium text-gray-900"
              >
                {{ category }}
              </label>
            </div>
            
            <div class="ml-6 space-y-2">
              <label
                v-for="permission in getPermissionsByCategory(category)"
                :key="permission.id"
                class="flex items-start"
              >
                <input
                  v-model="formData.permissionIds"
                  type="checkbox"
                  :value="permission.id"
                  class="mt-0.5 rounded border-gray-300 text-blue-600 shadow-sm focus:border-blue-300 focus:ring focus:ring-blue-200 focus:ring-opacity-50"
                >
                <div class="ml-2">
                  <div class="text-sm text-gray-700">{{ permission.name }}</div>
                  <div class="text-xs text-gray-500">{{ permission.description }}</div>
                </div>
              </label>
            </div>
          </div>
        </div>

        <p v-if="errors.permissionIds" class="text-sm text-red-600">
          {{ errors.permissionIds }}
        </p>

        <div class="text-sm text-gray-500">
          已选择 {{ formData.permissionIds.length }} 个权限
        </div>
      </div>

      <!-- 操作按钮 -->
      <div class="flex justify-end space-x-3 pt-4 border-t">
        <button
          type="button"
          @click="$emit('close')"
          class="btn-secondary"
        >
          取消
        </button>
        <button
          type="submit"
          :disabled="loading"
          class="btn-primary"
        >
          <i v-if="loading" class="w-4 h-4 mr-2 animate-spin mdi:loading" />
          {{ role ? '更新' : '创建' }}
        </button>
      </div>
    </form>
  </Modal>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import Modal from '@/components/Modal.vue'

interface Role {
  id: string
  name: string
  description: string
  permissions: string[]
  status: 'active' | 'inactive'
}

interface Permission {
  id: string
  name: string
  description: string
  category: string
}

interface Props {
  role?: Role | null
  permissions: Permission[]
}

const props = defineProps<Props>()
const emit = defineEmits<{
  close: []
  save: [data: any]
}>()

const loading = ref(false)

const formData = reactive({
  name: '',
  description: '',
  status: 'active' as 'active' | 'inactive',
  permissionIds: [] as string[]
})

const errors = reactive({
  name: '',
  description: '',
  permissionIds: ''
})

// 权限分类
const permissionCategories = computed(() => {
  const categories = new Set(props.permissions.map(p => p.category))
  return Array.from(categories)
})

// 根据分类获取权限
const getPermissionsByCategory = (category: string) => {
  return props.permissions.filter(p => p.category === category)
}

// 检查分类是否全选
const isCategorySelected = (category: string) => {
  const categoryPermissions = getPermissionsByCategory(category)
  return categoryPermissions.length > 0 && 
         categoryPermissions.every(p => formData.permissionIds.includes(p.id))
}

// 检查分类是否部分选中
const isCategoryIndeterminate = (category: string) => {
  const categoryPermissions = getPermissionsByCategory(category)
  const selectedCount = categoryPermissions.filter(p => formData.permissionIds.includes(p.id)).length
  return selectedCount > 0 && selectedCount < categoryPermissions.length
}

// 切换分类选择
const toggleCategory = (category: string) => {
  const categoryPermissions = getPermissionsByCategory(category)
  const isSelected = isCategorySelected(category)
  
  if (isSelected) {
    // 取消选择该分类下的所有权限
    categoryPermissions.forEach(p => {
      const index = formData.permissionIds.indexOf(p.id)
      if (index > -1) {
        formData.permissionIds.splice(index, 1)
      }
    })
  } else {
    // 选择该分类下的所有权限
    categoryPermissions.forEach(p => {
      if (!formData.permissionIds.includes(p.id)) {
        formData.permissionIds.push(p.id)
      }
    })
  }
}

// 全选权限
const selectAllPermissions = () => {
  formData.permissionIds = props.permissions.map(p => p.id)
}

// 清空权限
const clearAllPermissions = () => {
  formData.permissionIds = []
}

// 监听角色数据变化，初始化表单
watch(() => props.role, (role) => {
  if (role) {
    formData.name = role.name
    formData.description = role.description
    formData.status = role.status
    // 根据权限名称找到对应的ID
    formData.permissionIds = props.permissions
      .filter(permission => role.permissions.includes(permission.name))
      .map(permission => permission.id)
  } else {
    // 重置表单
    Object.assign(formData, {
      name: '',
      description: '',
      status: 'active',
      permissionIds: []
    })
  }
  // 清除错误
  Object.keys(errors).forEach(key => {
    errors[key] = ''
  })
}, { immediate: true })

// 验证表单
const validateForm = () => {
  let isValid = true
  
  // 清除之前的错误
  Object.keys(errors).forEach(key => {
    errors[key] = ''
  })

  // 验证角色名称
  if (!formData.name.trim()) {
    errors.name = '请输入角色名称'
    isValid = false
  } else if (formData.name.length < 2) {
    errors.name = '角色名称至少2个字符'
    isValid = false
  }

  // 验证描述
  if (!formData.description.trim()) {
    errors.description = '请输入角色描述'
    isValid = false
  }

  // 验证权限
  if (formData.permissionIds.length === 0) {
    errors.permissionIds = '请至少选择一个权限'
    isValid = false
  }

  return isValid
}

// 提交表单
const handleSubmit = async () => {
  if (!validateForm()) {
    return
  }

  loading.value = true
  try {
    // 准备提交数据
    const submitData = {
      name: formData.name,
      description: formData.description,
      status: formData.status,
      permissionIds: formData.permissionIds,
      // 将权限ID转换为权限名称
      permissions: props.permissions
        .filter(p => formData.permissionIds.includes(p.id))
        .map(p => p.name)
    }

    emit('save', submitData)
  } catch (error) {
    console.error('提交失败:', error)
  } finally {
    loading.value = false
  }
}
</script>